package com.tanglongan.concurrent._sync;

import lombok.AllArgsConstructor;

public class Sync02 {
    public static void main(String[] args) {
        Sync01Service serviceA = new Sync01Service();
        Sync01Service serviceB = new Sync01Service();
        Thread a = new Sync01Thread(serviceA, "a");
        Thread b = new Sync01Thread(serviceB, "b");

        a.start();
        b.start();
    }
}

class Sync02Service {
    private int num;

    synchronized public void add(String username) {
        if ("a".equals(username)) {
            num = 100;
            System.out.println("a is set");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            num = 200;
            System.out.println("b is set");
        }
        System.out.println("username=" + username + ", num=" + num);
    }
}

@AllArgsConstructor
class Sync02Thread extends Thread {
    private Sync01Service service;
    private String username;

    @Override
    public void run() {
        service.add(this.username);
    }
}


